package adminorg;

import com.oros.db.AETableContainer;

import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table;
import com.vaadin.ui.Tree;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Table.TableDragMode;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.themes.Runo;
import com.vaadin.data.util.filter.Compare.Equal;
import com.vaadin.event.DataBoundTransferable;
import com.vaadin.event.dd.DragAndDropEvent;
import com.vaadin.event.dd.DropHandler;
import com.vaadin.event.dd.acceptcriteria.AcceptAll;
import com.vaadin.event.dd.acceptcriteria.AcceptCriterion;

public class StatisticUse extends VerticalLayout{
	/**
	 * 
	 */
	private static final long serialVersionUID = -1073400831503213553L;

	private VerticalLayout MainForm = null;
	private DatabaseHelper dbHelp = null;
	private ComboBox CompCombo = null;
	private HorizontalSplitPanel StatUsePanel = null;
	private HorizontalSplitPanel StatPanel = null;
	private Panel treePanel = null;
	private Tree tree = null;
	private Table statUseTable = null;
	private Table statDictTable = null;
	private Button bRefresh = null;
	
	public StatisticUse(DatabaseHelper dbHelper){
		MainForm = new VerticalLayout();
		//MainForm.setSizeFull();
		HorizontalLayout HL = new HorizontalLayout();
		HL.setWidth("100%");
		this.dbHelp = dbHelper;
		bRefresh = new Button(dbHelp.getWords("Refresh"),new Button.ClickListener(){
			/**
			 * 
			 */
			private static final long serialVersionUID = -6591326305761866118L;

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				try {
					dbHelp.getCompContainer().refresh();
					dbHelp.getCompAccContainer().refresh();
					dbHelp.getOrgschemaContainer().refresh();
					dbHelp.getDictStatisticContainer().refresh();					
					dbHelp.getStatisticUsesContainer().refresh();
					dbHelp.getOrgLevelContainer().refresh();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}});
		HL.addComponent(bRefresh);
		HL.setComponentAlignment(bRefresh, Alignment.TOP_LEFT);
		CompCombo = new ComboBox();
		CompCombo.setImmediate(true);
		CompCombo.setNullSelectionAllowed(false);
		try {
			CompCombo.setContainerDataSource(dbHelp.getCompContainer());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		CompCombo.setItemCaptionPropertyId("name");
		HL.addComponent(CompCombo);
		HL.setComponentAlignment(CompCombo, Alignment.TOP_RIGHT);
		MainForm.addComponent(HL);
		MainForm.setComponentAlignment(HL, Alignment.TOP_LEFT);
		StatUsePanel = new HorizontalSplitPanel();
		//StatUsePanel.setSizeFull();
		try {
			tree = new Tree(dbHelp.getWords("Posts"),dbHelp.views.getOrgschemaHierarchicalContainer());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			tree.setContainerDataSource(dbHelp.views.getOrgschemaHierarchicalContainer());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tree.setItemCaptionPropertyId("orgschema.name");
		tree.setHeight("800px");
		tree.setCaption(dbHelp.getWords("PostsOrganization"));
		treePanel = new Panel();
		treePanel.setContent(StatUsePanel);
		StatUsePanel.setFirstComponent(tree);
		StatUsePanel.setSplitPosition(30);
		StatPanel=new HorizontalSplitPanel();
		try {
			statUseTable = new Table(dbHelp.getWords("Assigned"),dbHelp.views.getStatisticUseViewContainer());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		statUseTable.setImmediate(true);
		try {
			statUseTable.setContainerDataSource(dbHelp.views.getStatisticUseViewContainer());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		statUseTable.setVisibleColumns(new Object[]{"statisticuses.code","dictstatistic.name"});
		statUseTable.setColumnHeaders(new String[]{dbHelp.getWords("Code"),dbHelp.getWords("Assigned")});
		statUseTable.setColumnCollapsingAllowed(true);
		statUseTable.setColumnReorderingAllowed(true);
		statUseTable.setDragMode(TableDragMode.ROW);
		statUseTable.setSelectable(true);
		statUseTable.setStyleName(Runo.TABLE_SMALL);
		//LUT = new VerticalLayout();
		//LPUT = new VerticalLayout();
		//LUT.addComponent(statUseTable);
		//statUseWrapper = new DragAndDropWrapper(LUT);
		//statUseWrapper = new DragAndDropWrapper(statUseTable);
		//LPUT.addComponent(statUseWrapper);
		//StatPanel.setFirstComponent(LPUT);
		StatPanel.setFirstComponent(statUseTable);
		//LPUT.setSizeFull();
		//statUseWrapper.setSizeFull();
		//LUT.setSizeFull();
		statUseTable.setSizeFull();
		
		try {
			statDictTable = new Table(dbHelp.getWords("Statistic"),dbHelp.getDictStatisticContainer());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		statDictTable.setImmediate(true);
		try {
			statDictTable.setContainerDataSource(dbHelp.getDictStatisticContainer());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		statDictTable.setVisibleColumns(new Object[]{"name"});
		statDictTable.setColumnHeaders(new String[]{dbHelp.getWords("Statistic")});
		statDictTable.setColumnCollapsingAllowed(true);
		statDictTable.setColumnReorderingAllowed(true);
		statDictTable.setSelectable(true);
		statDictTable.setStyleName(Runo.TABLE_SMALL);
		statDictTable.setDragMode(TableDragMode.ROW);
		statDictTable.setSizeFull();
		StatPanel.setSecondComponent(statDictTable);
		StatPanel.setHeight("800px");
		StatUsePanel.setSecondComponent(StatPanel);
		/////
		MainForm.addComponent(treePanel);
		MainForm.setComponentAlignment(treePanel, Alignment.TOP_LEFT);
		MainForm.setStyleName(Runo.CSSLAYOUT_SHADOW);
		addStatUseDrop();
		addTreeListener();
		tree.setImmediate(true);
		addCompanyListeners();
		try {
			CompCombo.select(dbHelp.getCompContainer().firstItemId());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	public VerticalLayout getStatisticUseForm(){
		return MainForm;
	};
	public void addCompanyListeners(){
		CompCombo.addListener(new Property.ValueChangeListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 3553727834189583715L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				// TODO Auto-generated method stub
				Object id = CompCombo.getValue();
				if (!(id instanceof Integer)){
					id = Integer.parseInt(id.toString());
				}
				if (!id.equals(dbHelp.getCompanyId())){
					try	{
					   dbHelp.setCompanyId(id);
					} catch(Exception e) {
			        	MainForm.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					} 
				}
				try {
					tree.select(dbHelp.views.getOrgschemaHierarchicalContainer().firstItemId());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
		dbHelp.addCompanyListener(new Property.ValueChangeListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = -4482321290539424815L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				// TODO Auto-generated method stub
				Object id = CompCombo.getValue();	
                if (id!=null && !(id instanceof Integer))
                {
               	 id = Integer.parseInt(id.toString());
                }
                if (id==null || !id.equals(dbHelp.getCompanyId()))
                {
               	 CompCombo.setValue(dbHelp.getCompanyId());
                }
			}
			
		});
	}
	
	private void statUseRefresh(Object Post){
		if (Post==null) return;
		try {
			dbHelp.views.getStatisticUseViewContainer().removeAllContainerFilters();
			dbHelp.views.getStatisticUseViewContainer().addContainerFilter(new Equal("statisticuses.postid",Post));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			MainForm.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
			e.printStackTrace();
		}
	}
	
	public void addTreeListener(){
		tree.addListener(new Property.ValueChangeListener(){
			/**
			 * 
			 */
			private static final long serialVersionUID = -7034989058487356218L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				if (event.getProperty().getValue()==null) return;
				// TODO Auto-generated method stub
				statUseRefresh(event.getProperty().getValue());
			}
			
		});
	}
	
	private void addStatUseDrop(){
		statUseTable.setDropHandler(new DropHandler(){
			/**
			 * 
			 */
			private static final long serialVersionUID = -8184684082831330057L;

			@Override
			public void drop(DragAndDropEvent event) {
				// TODO Auto-generated method stub
				DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
				Object sourceItemId = t.getItemId();
				if (!((AETableContainer) t.getSourceContainer()).tableName.equals("dictstatistic")) return;
				try {
					dbHelp.views.getStatisticUseViewContainer().rollback();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try {
					
					Object tempId = dbHelp.views.getStatisticUseViewContainer().addItem();
					dbHelp.views.getStatisticUseViewContainer().setPropertiesOfItem(tempId, 
							"statisticuses.postid", Integer.parseInt(tree.getValue().toString()));
					dbHelp.views.getStatisticUseViewContainer().setPropertiesOfItem(tempId, 
							"statisticuses.code", tree.getContainerProperty(tree.getValue(), 
									"orgschema.code").getValue().toString().concat("-").concat(
									dbHelp.getDictStatisticContainer().getContainerProperty(
											sourceItemId, "code").getValue().toString()));
					dbHelp.views.getStatisticUseViewContainer().setPropertiesOfItem(tempId, 
							"statisticuses.statid", Integer.parseInt(sourceItemId.toString()));
					dbHelp.views.getStatisticUseViewContainer().setPropertiesOfItem(tempId, 
							"statisticuses.active", true);
					dbHelp.views.getStatisticUseViewContainer().commit();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					MainForm.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					e.printStackTrace();
				}
			}

			@Override
			public AcceptCriterion getAcceptCriterion() {
				// TODO Auto-generated method stub
				return  AcceptAll.get();
			}
			
		});
		statDictTable.setDropHandler(new DropHandler(){
			/**
			 * 
			 */
			private static final long serialVersionUID = -7364120477613779441L;

			@Override
			public void drop(DragAndDropEvent event) {
				// TODO Auto-generated method stub
				DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
				Object sourceItemId = t.getItemId();
				if (((AETableContainer) t.getSourceContainer()).tableName.equals("dictstatistic")) return;
				try {
					dbHelp.views.getStatisticUseViewContainer().rollback();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					dbHelp.views.getStatisticUseViewContainer().removeItem(sourceItemId,0);
					dbHelp.views.getStatisticUseViewContainer().commit();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					MainForm.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
				}
			}

			@Override
			public AcceptCriterion getAcceptCriterion() {
				// TODO Auto-generated method stub
				return  AcceptAll.get();
			}
			
		});
		
	}
	
	
}
